package user;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.faces.bean.ManagedBean;
import java.util.List;
import javax.faces.bean.CustomScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import lecture.Lecture; 
import lecture.LectureManagedBean;

/**
 *
 * @author Thorsten Ludwig
 */

@ManagedBean(name="editRoleBean")
@CustomScoped(value="#{window}")
public class EditRoleManagedBean {
    
    private User selectedUser;
    
    public List<UserRoleContainer> getUserTupel() {
        FacesContext c = FacesContext.getCurrentInstance();
        LectureManagedBean lb = c.getApplication().evaluateExpressionGet(c, "#{lectureBean}", LectureManagedBean.class);
        Lecture lecture = lb.getLecture();
        List<UserRoleContainer> list = new ArrayList<UserRoleContainer>();
        for(User user: lecture.getInfo().getUsers()) {
            System.out.println("Name " + user.getUsername());
            list.add(new UserRoleContainer(user,user.getUserRole(lecture.getInfo().getName()), lecture));
        }
        System.out.println("Größe der Liste: " + list.size());
        this.sort(list);
        return list;
    }
    
    public List<SelectItem> getRoleItems() {
        List<SelectItem> list = new ArrayList<SelectItem>();
        list.add(new SelectItem(Role.ADMIN, "Admin"));
        list.add(new SelectItem(Role.COADMIN, "Co-Admin"));
        list.add(new SelectItem(Role.TUTOR, "Tutor"));
        list.add(new SelectItem(Role.STUDENT, "Student"));
        return list;
    }

    private void sort(List<UserRoleContainer> list) {
        Collections.sort(list, new Comparator() {

            @Override
            public int compare(Object o1, Object o2) {
                UserRoleContainer t1 = (UserRoleContainer) o1;
                UserRoleContainer t2 = (UserRoleContainer) o2;
                
                if (t1.getRole().getValue() < t2.getRole().getValue())
                    return 1;
                else if (t1.getRole().getValue() > t2.getRole().getValue() )
                    return -1;
                else
                    return t1.getUser().getLastName().compareToIgnoreCase(t2.getUser().getLastName());
            }
        });
    }

    public User getSelectedUser() {
        System.out.println("Frage User ab");
        return selectedUser;
    }
    
    public void viewDetails(User u) {
        this.selectedUser = u;
    }
    
    public void back() {
        this.selectedUser = null;
    }
}